﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
using Pyramid.Bll;
using Pyramid.Models;
using System.Data.Entity;

namespace Pyramid.Controllers
{
	public class CustomerHealthController : BaseController
	{
		private readonly CustomerHelper _helper=new CustomerHelper();

		public ActionResult List(CustomerQueryModel model)
		{
			var customers = _helper.Query(model, User);

			var currentPage = (model.PageNum ?? 1) - 1;
			var pageSize = model.NumPerPage ?? 20;

			var vm = new PagerModel
				{
					PageSize = pageSize,
					CurrentPageIndex = currentPage,
					TotalCount = customers.Count()
				};
			ViewBag.Bag = vm;
			ViewBag.QueryModel = model;

			return View(customers.OrderBy(x => x.CreateTime).Skip(currentPage*pageSize).Take(pageSize).ToList());
		}

		/// <summary>
		/// 顾客健康档案首页
		/// </summary>
		/// <param name="id">顾客ID</param>
		public ActionResult HealthIndex(int id)
		{
			var customer = Db.Customers.First(x => x.Id == id);
			ViewBag.MasterId = GetMaster(id).Id;
			return View(customer);
		}

		/// <summary>
		/// 健康状况
		/// </summary>
		/// <param name="id">档案 master id</param>
		public ActionResult HealthBaseInfo(int id)
		{
			var master = Db.CustomerHealthArchiveMasters.First(x => x.Id == id);
			ViewBag.HumanBodySystemOptions = GetHumanBodySytemOptions();
			return View(master);
		}

		/// <summary>
		/// 编辑健康状况基本信息
		/// </summary>
		[HttpPost]
		public ActionResult EditHealthBaseInfo(CustomerHealthArchiveMaster model, int[] selectedConditions)
		{
			if (selectedConditions != null && selectedConditions.Length > 0)
			{
				model.HumanBodySystem = JsonConvert.SerializeObject(selectedConditions);
			}
			model.EditUserId = User.UserId;
			model.EditTime = DateTime.Now;
			Db.Entry(model).State = EntityState.Modified;
			Db.SaveChanges();

			return JSuccess();
		}

		#region 专家诊断
		/// <summary>
		/// 顾客的专家诊断列表
		/// </summary>
		/// <param name="id">档案 master id</param>
		public ActionResult ExpertDiagnosisRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.ExpertDiagnosisRecords.Where(x => x.MasterId == id));
		}

		public ActionResult CreateExpertDiagnosisRecord(int masterId)
		{
			var model = new ExpertDiagnosisRecord {MasterId = masterId};
			return View("EditExpertDiagnosisRecord", model);
		}

		public ActionResult EditExpertDiagnosisRecord(int id)
		{
			var model = Db.ExpertDiagnosisRecords.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult EditExpertDiagnosisRecord(ExpertDiagnosisRecord model)
		{
			if (model.Id == 0)
			{
				Db.ExpertDiagnosisRecords.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();

			return JSuccess("操作成功！", string.Format("tab_expertdiagnosisrecord_{0}", model.MasterId));
		}

		public ActionResult DeleteExpertDiagnosisRecord(int id, int masterId)
		{
			var model = new ExpertDiagnosisRecord {Id = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", string.Format("tab_expertdiagnosisrecord_{0}", masterId));
		}

		#endregion

		#region 疗程设计

		public ActionResult TreatmentPlanList(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.TreatmentPlans.Where(x => x.MasterId == id));
		}

		public ActionResult CreateTreatmentPlan(int masterId)
		{
			var model = new TreatmentPlan {MasterId = masterId, MaterialDate = DateTime.Now};
			return View("EditTreatmentPlan", model);
		}

		public ActionResult EditTreatmentPlan(int id)
		{
			var model = Db.TreatmentPlans.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult EditTreatmentPlan(TreatmentPlan model)
		{
			if (model.Id == 0)
			{
				Db.TreatmentPlans.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();

			return JSuccess("操作成功！", string.Format("tab_treatmentplan_{0}", model.MasterId));
		}

		public ActionResult DeleteTreatmentPlan(int id, int masterId)
		{
			var model = new TreatmentPlan {Id = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", string.Format("tab_treatmentplan_{0}", masterId));
		}

		#endregion

		#region 顾客健康管理记录

		public ActionResult HealthManageRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.CustomerHealthManageRecords.Where(x => x.MasterId == id));
		}

		public ActionResult CreateHealthManageRecord(int masterId)
		{
			var model = new CustomerHealthManageRecord {MasterId = masterId, DateTime = DateTime.Now};
			return View("EditHealthManageRecord",model);
		}

		public ActionResult EditHealthManageRecord(int id)
		{
			var model = Db.CustomerHealthManageRecords.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult EditHealthManageRecord(CustomerHealthManageRecord model)
		{
			if (model.Id == 0)
			{
				Db.CustomerHealthManageRecords.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();

			return JSuccess("操作成功！", string.Format("tab_customerhealthmanagerecord_{0}", model.MasterId));
		}

		public ActionResult DeleteHealthManageRecord(int id, int masterId)
		{
			var model = new CustomerHealthManageRecord { Id = id };
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", string.Format("tab_customerhealthmanagerecord_{0}", masterId));
		}

		#endregion

		#region 顾客回访记录

		public ActionResult ReturnVisitRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.ReturnVisitRecords.Where(x => x.MasterId == id));
		}

		public ActionResult CreateReturnVisitRecord(int masterId)
		{
			var model = new ReturnVisitRecord {MasterId = masterId, VisitDate = DateTime.Now};
			return View("EditReturnVisitRecord", model);
		}

		public ActionResult EditReturnVisitRecord(int id)
		{
			var model = Db.ReturnVisitRecords.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult EditReturnVisitRecord(ReturnVisitRecord model)
		{
			if (model.Id == 0)
			{
				Db.ReturnVisitRecords.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();

			return JSuccess("操作成功！", string.Format("tab_returnvisitrecord_{0}", model.MasterId));
		}

		public ActionResult DeleteReturnVisitRecord(int id, int masterId)
		{
			var model = new ReturnVisitRecord { Id = id };
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", string.Format("tab_returnvisitrecord_{0}", masterId));
		}

		#endregion

		#region 我的健康档案
		/// <summary>
		/// 我的健康档案 (首页)
		/// </summary>
		public ActionResult MyHealthInfo()
		{
			if (User.UserType != UserTypes.Customer)
				return NoAuthorization("此功能仅对直接客户开放！");

			var customer = Db.Customers.FirstOrDefault(x => x.Id == User.ExtInfoId);
			if (customer == null) return Error("关联的顾客资料已丢失，请联系管理员！");
			ViewBag.MasterId = GetMaster(User.ExtInfoId).Id;
			return View(customer);
		}

		/// <summary>
		/// 我的健康状况
		/// </summary>
		/// <param name="id">档案 master id</param>
		public ActionResult MyHealthBaseInfo(int id)
		{
			var master = Db.CustomerHealthArchiveMasters.First(x => x.Id == id);
			ViewBag.HumanBodySystemOptions = GetHumanBodySytemOptions();
			return View(master);
		}

		/// <summary>
		/// 我的专家诊断列表
		/// </summary>
		/// <param name="id">档案 master id</param>
		public ActionResult MyExpertDiagnosisRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.ExpertDiagnosisRecords.Where(x => x.MasterId == id));
		}

		public ActionResult MyTreatmentPlanList(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.TreatmentPlans.Where(x => x.MasterId == id));
		}

		public ActionResult MyHealthManageRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.CustomerHealthManageRecords.Where(x => x.MasterId == id));
		}

		public ActionResult MyReturnVisitRecords(int id)
		{
			ViewBag.MasterId = id;
			return View(Db.ReturnVisitRecords.Where(x => x.MasterId == id));
		}

		#endregion

		protected CustomerHealthArchiveMaster GetMaster(int customerId)
		{
			var master = Db.CustomerHealthArchiveMasters.FirstOrDefault(x => x.CustomerId == customerId);
			if (master != null) return master;
			var customer = Db.Customers.Single(x => x.Id == customerId);
			master = new CustomerHealthArchiveMaster
			{
				CustomerId = customerId,
				CustomerCode = customer.Code,
				CustomerFullName = customer.FullName,
				CreateTime = DateTime.Now,
				CreateUserId = User.UserId,
				EditTime = DateTime.Now,
				EditUserId = User.UserId
			};

			Db.CustomerHealthArchiveMasters.Add(master);
			Db.SaveChanges();

			return master;
		}

		protected IEnumerable<HumanBodySystem> GetHumanBodySytemOptions()
		{
			return Db.HumanBodySystems.Include(x => x.HealthConditions);
		}
	}
}